package com.ljh.account.controller;


import com.github.pagehelper.PageInfo;
import com.ljh.account.dao.Expense;
import com.ljh.account.dao.Resp.ExpenseResp;
import com.ljh.account.service.ExpenseService;
import com.ljh.account.utils.Response;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/api/protected")
public class ExpenseController {
    @Autowired
    private ExpenseService expenseService;

    @GetMapping("/expenses")
    public Response getExpensesWithFilter(
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) Integer bankAccountId,
            @RequestParam(required = false) BigDecimal minAmount,
            @RequestParam(required = false) BigDecimal maxAmount,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request
            ) {
        Object userId = request.getAttribute("userId");

        PageInfo pageInfo = expenseService.getExpensesWithFilter((Long) userId, categoryId, bankAccountId, minAmount, maxAmount, page, size);
        return Response.success(pageInfo);
    }

    @GetMapping("/{id}")
    public Response getExpenseById(@PathVariable int id) {
        ExpenseResp res = expenseService.getExpenseById(id);
        return  Response.success(res);
    }

    @PostMapping("/expenses")
    public Response addExpense(@RequestBody Expense expense,HttpServletRequest request) {
        Object userId = request.getAttribute("userId");
        expense.setUserId((Long) userId);
        expenseService.addExpense(expense);
        return Response.success("新增成功！");
    }

    @PutMapping("/{id}")
    public void updateExpense(@PathVariable int id, @RequestBody Expense expense) {
        expense.setId(id);
        expenseService.updateExpense(expense);
    }

    @DeleteMapping("/expenses")
    public Response deleteExpense(@RequestParam Long id) {
        expenseService.deleteExpense(id);
        return Response.success("删除成功!");
    }
}